<template>
  <div class="vx-acronym-index" flex>
    <div class="scroll-container" ref="scrollContainer" @scroll="scrollList">
      <slot />
    </div>
    <div class="abc-index">
      <div
        @click="changeCurrentAbcIndex(abcIndex)"
        class="abc-index-item"
        :class="{ 'abc-index-item-active': abcIndex == currentAbcIndex }"
        v-for="abcIndex in abcIndexList"
        :key="abcIndex"
      >
        {{ abcIndex }}
      </div>
    </div>
  </div>
</template>

<script>
import { pinyin, debounce } from '@csii/vx-util';
const ABC = 'abcdefghijklmnopqrstuvwxyz'.toUpperCase();
export default {
  name: 'vx-acronym-index',
  props: {
    list: {
      type: Array,
      default: function() {
        return [];
      },
    },
  },
  data() {
    return {
      abcIndexList: (ABC + '#').split(''), // 索引目录
      currentAbcIndex: 'A', // 当前索引序号
    };
  },
  methods: {
    // 手动点击索引，触犯滚动条滚动到对应元素
    changeCurrentAbcIndex(val) {
      const index = this.list.findIndex((item) => {
        const startChar = pinyin
          .CC2PY(item.name)
          .join()
          .substr(0, 1);
        if (val == '#') {
          return !ABC.includes(startChar);
        } else {
          return startChar == val;
        }
      });
      let heightSum = 0;
      for (let i = 0; i < index; i++) {
        const item = this.list[i];
        heightSum += item.height;
      }
      this.$refs.scrollContainer.scrollTop = heightSum;
      this.currentAbcIndex = val;
    },
    // 鼠标滚动索引内容，索引序号自动定位
    scrollList: debounce(function() {
      let heightSum = 0;
      for (let i = 0; i < this.list.length; i++) {
        const item = this.list[i];
        heightSum += item.height;
        if (heightSum > this.$refs.scrollContainer.scrollTop) {
          this.currentAbcIndex = pinyin
            .CC2PY(item.name)
            .join()
            .substr(0, 1);
          return;
        }
      }
    }, 200),
  },
};
</script>

<style lang="scss">
.vx-acronym-index {
  margin-right: -10px;
  .abc-index {
    text-align: center;
    font-size: 11px;
    color: $color-text-sub;
    margin-left: 5px;
    flex: none;
    .abc-index-item {
      height: 16px;
      width: 16px;
      line-height: 16px;
      border-radius: 50%;
      margin-top: 5px;
      cursor: pointer;
    }
    .abc-index-item-active {
      background: rgba(59, 76, 135, 0.5);
      color: $color-text-primary;
    }
  }
  .scroll-container {
    height: 600px;
    overflow: auto;
    flex: 1;
  }
}
</style>
